﻿namespace Sai.Core.Reporting
{
    using System;
    using System.IO;

	/// <summary>
	/// Generates report output as Html documents.
	/// </summary>
	public class HtmlReportFormatter : IReportFormatter
	{
		/// <summary>
		/// Content to replace in between <head></head> tags.
		/// </summary>
		public string HeadContent
		{
			get;
			set;
		}

		/// <summary>
		/// Content to replace in between <style></style> tags.
		/// </summary>
		public string StyleContent
		{
			get;
			set;
		}

		/// <summary>
		/// Custom text at the top of the report.
		/// </summary>
		public string HeaderText
		{
			get;
			set;
		}

		/// <summary>
		/// Custom text at the bottom of the report.
		/// </summary>
		public string FooterText
		{
			get;
			set;
		}

		public string Extension
		{
			get { return ".html"; }
		}

		public void Execute(IFlattenToXml flattenable, IReportTransformation transformation, IReportOutput output)
		{
            try
            {
                this.Save(transformation.Transform(flattenable), output);
            }
            catch (Exception ex)
            {
                throw new ReportGenerationException(string.Format("Error generating Html report to {0}", output.Path), ex);
            }
        }

		private void Save(string htmlOutput, IReportOutput output)
		{
            // add links to styles,
            // add links to js
            // add links to product
            if (!string.IsNullOrEmpty(this.HeadContent))
            {
                TagContentReplacer replacer = new TagContentReplacer("head");
                htmlOutput = replacer.ReplaceWith(htmlOutput, this.HeadContent);
            }

            if (!string.IsNullOrEmpty(this.StyleContent))
			{
				TagContentReplacer replacer = new TagContentReplacer("style");
				htmlOutput = replacer.ReplaceWith(htmlOutput, this.StyleContent);
			}

			if (!string.IsNullOrEmpty(this.HeaderText))
			{
				TagContentReplacer replacer = new TagContentReplacer("header");
				htmlOutput = replacer.ReplaceWith(htmlOutput, this.HeaderText);
			}

			if (!string.IsNullOrEmpty(this.FooterText))
			{
				TagContentReplacer replacer = new TagContentReplacer("footer");
				htmlOutput = replacer.ReplaceWith(htmlOutput, this.FooterText);
			}

			output.Execute(htmlOutput);
		}
	}
}
